﻿using System;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;
using Utils;

namespace TimeBarPlugin
{
	internal class DecisionEngineDataSource
	{
		#region Public Methods

		public void Save(DecisionEngineData data)
		{
			BinaryFormatter formatter = new BinaryFormatter();

			using (FileStream stream = new FileStream(Assembly.GetExecutingAssembly().GetName().Name + Properties.Settings.Default.RealtimeEngineDataFilename, FileMode.OpenOrCreate))
			{
				formatter.Serialize(stream, data);
			}
		}

		public DecisionEngineData Load()
		{
			DecisionEngineData result;

			if (this.IsDataToLoad())
			{
				BinaryFormatter formatter = new BinaryFormatter();

				using (FileStream stream = new FileStream(Assembly.GetExecutingAssembly().GetName().Name + Properties.Settings.Default.RealtimeEngineDataFilename, FileMode.OpenOrCreate))
				{
					try
					{
						result = (DecisionEngineData)formatter.Deserialize(stream);
					}
					catch (Exception ex)
					{
						ExceptionLogger.LogException("There was an error getting the engine data from the file " + Assembly.GetExecutingAssembly().GetName().Name + Properties.Settings.Default.RealtimeEngineDataFilename + ". Returning empty data", ex, false);
						result = new DecisionEngineData();
					}
				}
			}
			else
			{
				result = new DecisionEngineData();
			}

			return result;
		}

		public bool IsDataToLoad()
		{
			return File.Exists(Assembly.GetExecutingAssembly().GetName().Name + Properties.Settings.Default.RealtimeEngineDataFilename);
		}

		#endregion
	}
}
